<template>
    <div class="ScreenViewManageEdit">
        <div class="ScreenViewManageEdit-head">
            <div class="ScreenViewManageEdit-head-le">
                <img src="@img/screen-logo.png"/>
                <span>{{ i18n("index.BIDesign", "BI设计") }}</span>
            </div>
            <div class="ScreenViewManageEdit-head-button">
                <div @click="state='pc'" class="ScreenViewManageEdit-button"
                     :class="{'ScreenViewManageEdit-button-hover':state=='pc'}">
                    <rx-icon-show icon="icon-fillcomputer_fill"></rx-icon-show>
                    {{ i18n("index.computerLayout", "电脑端布局") }}
                </div>
                <div @click="state='mobile'" class="ScreenViewManageEdit-button"
                     :class="{'ScreenViewManageEdit-button-hover':state=='mobile'}">
                    <rx-icon-show icon="icon-fillmobilephone_fill"></rx-icon-show>
                    {{ i18n("index.mobileLayout", "移动端布局") }}
                </div>
            </div>
            <div class="ScreenViewManageEdit-head-ri">
                <div @click="recall" class="ScreenViewManageEdit-head-ri-button"
                     :class="{'ScreenViewManageEdit-head-ri-button-forbid':curIndex===0}">
                    <rx-icon-show class="ScreenViewManageEdit-head-ri-button-iconfont"
                                  icon="icon-lineVue3_revocation"></rx-icon-show>
                    <span>{{ i18n("index.withdraw", "撤回") }}</span>
                </div>
                <div @click="reform" class="ScreenViewManageEdit-head-ri-button"
                     :class="{'ScreenViewManageEdit-head-ri-button-forbid':curIndex === operationLogs.length - 1}">
                    <rx-icon-show class="ScreenViewManageEdit-head-ri-button-iconfont"
                                  icon="icon-lineVue3_renewal"></rx-icon-show>
                    <span>{{ i18n("index.redo", "重做") }}</span>
                </div>
                <div @click="getHistory" class="ScreenViewManageEdit-head-ri-button" v-if="screenView.pkId">
                    <rx-icon-show class="ScreenViewManageEdit-head-ri-button-iconfont"
                                  icon="icon-linetime"></rx-icon-show>
                    <span>{{ i18n("index.history", "历史记录") }}</span>
                </div>
                <div @click="save(true)" class="ScreenViewManageEdit-head-ri-button">
                    <rx-icon-show class="ScreenViewManageEdit-head-ri-button-iconfont"
                                  icon="icon-lineicon-test"></rx-icon-show>
                    <span>{{ i18n("index.savePreview", "保存&预览") }}</span>
                </div>
                <div @click="save(false)" class="ScreenViewManageEdit-head-ri-button">
                    <rx-icon-show class="ScreenViewManageEdit-head-ri-button-iconfont"
                                  icon="icon-lineVue3jpaas-icon_baocun"></rx-icon-show>
                    <span>{{ $ti18('rxForm.saveBtn', '保存') }}</span>
                </div>
                <div @click="emit" class="ScreenViewManageEdit-head-ri-button">
                    <rx-icon-show class="ScreenViewManageEdit-head-ri-button-iconfont"
                                  icon="icon-linetuihui"></rx-icon-show>
                    <span>{{ i18n("index.exit", "退出") }}</span>
                </div>
            </div>
        </div>
        <!--pc端配置页面-->
        <div style="display: contents;" v-show="state=='pc'">
            <!--栏目-->
            <div class="ScreenViewManageEdit-control">
                <div class="ScreenViewManageEdit-control-common-type" v-for="(item,index) in componentList"
                     :key="index">
                    <div class="ScreenViewManageEdit-control-common" @click="add(item)">
                        <rx-icon-show class="ScreenViewManageEdit-control-icon" :icon="item.icon"></rx-icon-show>
                        <span class="ScreenViewManageEdit-control-name">{{ item.title }}</span>
                    </div>
                    <!--组件分类-->
                    <div class="componentList-child" v-if="item.childList">
                        <div class="componentList-child-commom" v-for="(obj,index1) in item.childList" :key="index1">
                            <div class="componentList-child-commom-hend">{{ obj.name }}</div>
                            <div class="componentList-child-commom-list">
                                <div class="componentList-child-commom-list-name" v-for="(list,index2) in obj.childList"
                                     :key="index2" @click="add(list)">
                                    <rx-icon-show :icon="list.icon"></rx-icon-show>
                                    <span>{{ list.title }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!--内容-->
            <div class="ScreenViewManageEdit-drag">
                <div :class="[spread?'ScreenViewManageEdit-drag-le':'ScreenViewManageEdit-drag-le-spread']">
                    <left-design @spreadClick="spreadClick" @pitchOnKey="pitchOnKey" @onBlur="onBlur" :spread="spread"
                                 :screenConfig="screenConfig"></left-design>
                </div>
                <div style="flex: 1" class="ScreenViewManageEdit-tab">
                    <a-tabs v-model:activeKey="designKey" size="small" @change="designKeyChange">
                        <a-tab-pane key="design" :tab="i18n('list.design','设计')">
                            <div class="ScreenViewManageEdit-drag-common" style="height: 100%;width: 100%" id="freedom">
                                <div class="ScreenViewManageEdit-drag-common-img"
                                     :style="{'background-color':screenConfig.globalConfig.background=='color'?screenConfig.globalConfig.customColor:''}">
                                    <img
                                        v-if="screenConfig.globalConfig.background=='system' &&screenConfig.globalConfig.mode=='dark'"
                                        class="system-img"
                                        :src="getImage('/image/background/dark'+screenConfig.globalConfig.bgImage+'.png')"/>
                                    <img
                                        v-else-if="screenConfig.globalConfig.background=='system' &&screenConfig.globalConfig.mode=='bright'"
                                        class="system-img"
                                        :src="getImage('/image/background/light'+screenConfig.globalConfig.bgImage+'.png')"/>
                                    <img v-else-if="screenConfig.globalConfig.background=='custom'" class="system-img"
                                         :src="getFilePath(screenConfig.globalConfig.customImage)" alt="photo"/>
                                </div>
                                <rx-drag v-if="screenConfig.components.length!=0" ref="drag" :key="keyShow"
                                         :dragList="screenConfig.components">
                                    <div v-for="(rect, index) in screenConfig.components" :key="index">
                                        <rxDragList
                                            @rxDrag="rxDrag"
                                            :dragShow="dragShow"
                                            :scrollWidth="scrollWidth"
                                            @loosenMouse="loosenMouse"
                                            @mouseup="mouseup(rect)"
                                            @refresh="refresh($event,rect)"
                                            :index="index"
                                            :dragList="screenConfig.components"
                                            @deselect="deselect"
                                            :child='false'
                                            :rect="rect"
                                        >
                                            <template v-slot:button v-if="!rect.child">
                                                <div
                                                    v-if="rect.config.styles.fullScreenShow && !fullScreenList.includes(rect.type)"
                                                    class="mobile-compile" @click="enlarge(rect)" title="全屏">
                                                    <rx-icon-show title="全屏" style="font-size:16px"
                                                                  icon="icon-linefullscreen"></rx-icon-show>
                                                </div>
                                                <div class="mobile-compile" @click="editComponent(rect)"
                                                     :title="$ti18('rxList.editBtn', '编辑')">
                                                    <rx-icon-show :title="$ti18('rxList.editBtn', '编辑')"
                                                                  style="font-size:16px"
                                                                  icon="icon-lineedit"></rx-icon-show>
                                                </div>
                                                <div class="mobile-compile" @click="copyComponent(rect)"
                                                     :title="i18n('index.copy','复制')">
                                                    <rx-icon-show :title="i18n('index.copy','复制')"
                                                                  style="font-size:16px"
                                                                  icon="icon-lineVue3_copy"></rx-icon-show>
                                                </div>
                                            </template>
                                            <template v-slot:content>
                                                <div v-if="!rect.child"
                                                     :class="[borderShow(rect.config.styles.background) || rect.config.styles.mode =='material' ||  rect.type== 'iconfont' ?'rx-dragList-common':'rx-dragList-common-system']"
                                                     :style="getStyle(rect.config.styles,rect.type)">
                                                    <!-- 控件内容-->
                                                    <component :is="rect.type+'-view'"
                                                               style="z-index:1;position: absolute;"
                                                               :ref="rect.id"
                                                               :screenView="screenView"
                                                               :screenConfig="screenConfig"
                                                               :config="rect.config"
                                                               :loadView="loadView"
                                                    ></component>
                                                </div>
                                                <div v-else>
                                                    <rxDragList
                                                        @refresh="refresh"
                                                        :dragShow="dragShow"
                                                        @loosenMouse="loosenMouse"
                                                        :scrollWidth="rect.width"
                                                        :scrollChildHeight="rect.height"
                                                        :index="index"
                                                        :index1="index1"
                                                        :dragList="screenConfig.components"
                                                        :key="index1"
                                                        :child='true'
                                                        :rect="rectChild" v-for="(rectChild, index1) in rect.child"
                                                    >
                                                        <template v-slot:button>
                                                            <div
                                                                v-if="rectChild.config.styles.fullScreenShow && !fullScreenList.includes(rectChild.type)"
                                                                class="mobile-compile" @click="enlarge(rectChild)"
                                                                title="全屏">
                                                                <rx-icon-show title="全屏" style="font-size:16px"
                                                                              icon="icon-linefullscreen"></rx-icon-show>
                                                            </div>
                                                            <div class="mobile-compile"
                                                                 @click="editComponent(rectChild)"
                                                                 :title="$ti18('rxList.editBtn', '编辑')">
                                                                <rx-icon-show :title="$ti18('rxList.editBtn', '编辑')"
                                                                              style="font-size:16px"
                                                                              icon="icon-lineedit"></rx-icon-show>
                                                            </div>
                                                        </template>
                                                        <template v-slot:content>
                                                            <div
                                                                :class="[borderShow(rectChild.config.styles.background) || rectChild.config.styles.mode =='material' ||  rectChild.type== 'iconfont' ?'rx-dragList-common':'rx-dragList-common-system']"
                                                                :style="getStyle(rectChild.config.styles,rectChild.type)">
                                                                <!-- 控件内容-->
                                                                <component :is="rectChild.type+'-view'"
                                                                           style="z-index:1;position: absolute;"
                                                                           :ref="rectChild.id"
                                                                           :screenView="screenView"
                                                                           :screenConfig="screenConfig"
                                                                           :config="rectChild.config"
                                                                           :loadView="loadView"
                                                                ></component>
                                                            </div>
                                                        </template>
                                                    </rxDragList>
                                                </div>
                                            </template>
                                        </rxDragList>
                                    </div>
                                </rx-drag>
                            </div>
                        </a-tab-pane>
                        <a-tab-pane key="jsScript" tab="JsScript">
                            <RxVueMonaco
                                ref="jsMonaco"
                                :value="screenView.jsScript"
                                language="javascript"
                                class="monacoEditor"
                                @change="jsScriptChange"
                            >
                                <template #toolbar>
                                    <div style="text-align: left;">
                                        <div>
                                            <a-dropdown :getPopupContainer="p=>p.parentNode">
                                                <template #overlay>
                                                    <a-menu>
                                                        <a-menu-item @click="addAjax('get')">get</a-menu-item>
                                                        <a-menu-item @click="addAjax('postForm')">postForm</a-menu-item>
                                                        <a-menu-item @click="addAjax('postJson')">postJson</a-menu-item>
                                                    </a-menu>
                                                </template>
                                                <a-button style="margin-left: 8px" size="small">
                                                    {{ insertScriptI18n('insertAjax', '插入AJAX函数') }}
                                                    <DownOutlined/>
                                                </a-button>
                                            </a-dropdown>
                                            <a-button size="small" style="margin-left: 8px"
                                                      @click="addInvokeCustomQuery">
                                                {{ insertScriptI18n('insertQuery', '插入调用查询') }}
                                            </a-button>
                                            <a-button size="small" style="margin-left: 8px" @click="addInvokeScript">
                                                {{ insertScriptI18n('insertScript', '插入调用脚本') }}
                                            </a-button>
                                        </div>
                                    </div>
                                </template>
                            </RxVueMonaco>
                        </a-tab-pane>
                    </a-tabs>
                </div>
                <div>
                    <!--页面对齐-->
                    <a-drawer
                        :closable="false"
                        :visible="pitchOn>=2"
                        :mask="false"
                        :width="300"
                        :destroyOnClose="true"
                    >
                        <grouping-design @groupingDesign="groupingDesign" :pitchOn="pitchOn"
                                         :components="screenConfig.components"
                                         :scrollWidth="scrollWidth"></grouping-design>
                    </a-drawer>
                    <a-drawer
                        class="right-design"
                        :closable="false"
                        :visible="visible"
                        :width="430"
                        @close="onClose"
                        :destroyOnClose="true"
                    >
                        <right-design ref="rightDesign" :screenConfig="screenConfig" :screenView="screenView"
                                      :curComponent="curComponent"></right-design>
                    </a-drawer>
                    <a-drawer
                        class="right-design"
                        :closable="false"
                        :visible="showHistory"
                        :width="430"
                        @close="onHistoryClose"
                        :destroyOnClose="true"
                    >
                        <screen-view-history :screenConfig="screenConfig" :viewId="screenView.pkId"
                                             :rollback-history="rollbackHistory"
                                             :versionsId="versionsId"></screen-view-history>
                    </a-drawer>
                </div>
            </div>
            <!--展开按钮-->
            <div class="drawer-button" @click.stop="visible=true">
                <rx-icon-show icon="icon-lineicon-test39"></rx-icon-show>
            </div>
        </div>
        <!--移动端配置页面-->
        <div style="flex: 1;overflow: hidden" v-if="state=='mobile'">
            <mobile-index @mobileObj="mobileObj" :mobileConfig="mobileConfig" :screenConfig="screenConfig"
                          :screenView="screenView"></mobile-index>
        </div>
        <!--全屏弹窗-->
        <full-screen @minification="minification" v-if="fullScreenShow" :fullScreenShow="fullScreenShow"
                     :screenView="screenView" :screenConfig="screenConfig" :fullScreen="fullScreen"  :loadView="loadView"></full-screen>
    </div>
</template>

<script>
import scriptInsert from "./js/script-insert";
import allComponents from "./js/all-components.js";
import rightComponent from "./index.js";
import leftDesign from "./left-design.vue"
import rightDesign from './right-design.vue';
import groupingDesign from "./grouping-design.vue";
import {debounce} from "lodash-es";
import PagePublic from "../js/page-public";
import {Util,TokenUtil, RxVueMonaco} from "@lowcode/jpaas-base-lib";
import defConfig from "@/views/modules/design/js/def-config";
import previewComponents from "@/views/modules/preview/index.js";
import CustomComponents from "@/views/modules/custom-components/index.js";
import ScreenViewManageApi from '@/api/screen/core/screen-view-manage.js';
import ScreenViewHistory from "@/views/modules/design/dialog/screen-view-history.vue"
import FullScreen from "@/views/modules/design/dialog/full-screen.vue";
import MobileIndex from "./mobile/mobile-index.vue"
import ScreenChartManageDialog from "@/views/modules/screen/dialog/screen-chart-manage-dialog.vue"
import {defData} from "@/views/modules/design/js/static-data.js";
import useMain from "../../../stores/use-main";
import {mapState} from 'pinia';
export default {
    name: 'screen-design',
    mixins: [scriptInsert, rightComponent, PagePublic, CustomComponents, previewComponents],
    components: {
        leftDesign,
        RxVueMonaco,
        rightDesign,
        ScreenViewHistory,
        FullScreen,
        MobileIndex,
        groupingDesign
    },
    computed: {
        ...mapState(useMain, ['appId'])
    },
    data() {
        return {
            //主键
            pkId: "",
            visible: false,
            //大屏
            screenView: {
                name: "",
                alias: "",
                categoryId: "",
                config: "",
                jsScript: "",
            },
            defJsScript: "export default {\n" +
                "   //" + this.insertScriptI18n('defaultJsDesc1', '数据定义') + "\n" +
                "    data(){\n" +
                "        return {\n" +
                "        }\n" +
                "    },\n" +
                "    //" + this.insertScriptI18n('defaultJsDesc2', '初始化时加载') + "\n" +
                "    created(){\n" +
                "    },\n" +
                "    //" + this.insertScriptI18n('defaultJsDesc7', '初始化时加载') + "\n" +
                "    mounted(){\n" +
                "    },\n" +
                "    //" + this.insertScriptI18n('defaultJsDesc3', '页面自定义函数') + "\n" +
                "    methods:{\n" +
                "    },\n" +
                "    //" + this.insertScriptI18n('defaultJsDesc5', '页面自定义观察函数') + "\n" +
                "    watch:{}\n" +
                "}",
            //大屏配置
            screenConfig: {
                //全局配置
                globalConfig: {
                    mode: "dark",//模式
                    colors: ['#4285f4', '#81c784', '#ffb74d', '#ff6464', '#ff8a65', '#eaff00', '#00ffd8', '#13aaf5', '#41d4fb', '#94ecfb'],//图表主题颜色
                    background: "system",//背景类型
                    bgImage: 1,//背景图,默认系统图的第1张
                    customImage: '',//自定义背景图
                    customColor: '#4285f4',//自定义背景颜色
                    opacity: 100,//背景颜色透明度
                    bgZoom: "system",//缩放方式
                },
                //组件配置
                components: [],
                //传入参数配置
                params: [],
            },
            //所有组件
            componentList: allComponents,
            spread: true,
            dragShow: false,
            keyShow: new Date().getTime(),
            scrollWidth: 1000,
            //当前编辑的组件
            curComponent: "",
            //历史记录
            showHistory: false,
            //操作记录
            operationLogs: [],
            //当前记录所在
            curIndex: 0,
            pitchOn: 0,
            versionsId: -1,//版本
            fullScreen: {},//全屏列表
            fullScreenShow: false,
            fullScreenList: ['text', 'quillEditor', 'realTime', 'weather', 'image', 'iconfont', 'filter'],
            state: 'pc',//pc,mobile
            mobileConfig: [],
            designKey: "design"
        }
    },
    created() {
        this.pkId = this.$route.params ? this.$route.params.pkId : "";
        if (this.pkId && this.pkId != "-1") {
            this.init();
        } else {
            this.screenView.jsScript = this.defJsScript;
            //操作记录
            this.addRecal(this.screenConfig);
        }
        //获取所有自定义组件
        let customComponents = [];
        let files = import.meta.globEager('@/views/modules/custom-components/**/*.json');
        for (let key in files) {
            let file = files[key]["default"];
            customComponents.push(
                {customName: file.name, title: file.comment, type: "custom", icon: 'icon-colorzidingyi'}
            )
        }
        this.componentList.map(item => {
            if (item.type == "custom") {
                item.childList[0].childList = customComponents;
            }
        })
    },
    mounted() {
        let odiv = document.getElementById('freedom');
        if (odiv) {
            this.scrollWidth = odiv.scrollWidth;
        }
        let self = this;
        window.onresize = () => {
            return (() => {
                this.$nextTick(() => {
                    let odiv = document.getElementById('freedom');
                    if (odiv) {
                        this.scrollWidth = odiv.scrollWidth;
                    }
                });
            })();
        };
        document.addEventListener("keydown", function (e) {
            //可以判断是不是mac，如果是mac,ctrl变为花键
            //event.preventDefault() 方法阻止元素发生默认的行为。
            if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
                e.preventDefault();
                //操作记录
                self.addRecal(self.screenConfig);
            }
        }, false);
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "designLang", key);
        },
        componentI18n(name, text, key) {
            return this.$ti18(name, text, "componentsLang", key);
        },
        //点击新增
        add(component) {
            if (component.childList) {
                return;
            }
            let config ={};
            //引入已有图表
            if(component.chartType=='screenChart'){
                this.introduceChart();
                return;
            }else if(component.config){
                config =Util.deepClone(component.config);
            }
            else {
                //取组件默认配置
                if (!defConfig[component.type]) {
                    this.$message.warning(this.i18n("msa.developmentTips", "当前组件正在开发中!"));
                    return;
                }
                config = JSON.parse(JSON.stringify(defConfig[component.type]));
                //图表类型
                if (component.chartType) {
                    config.chartType = component.chartType;
                    config.dataSources.staticData=defData[config.chartType]?JSON.stringify(defData[config.chartType]):""
                } else if (component.type == "custom") { //自定义组件
                    config.customName = component.customName;
                }
            }
            config.key = Util.randomId();
            config.title = component.title + config.key;
            //组件默认配置
            let styleDef = {
                background: "system",//背景类型
                bgImage: 1,//背景图,默认系统图的第1张
                customImage: '',//自定义背景图
                customColor: '#4285f4',//自定义背景颜色
                borderColor: '#4285f4',//边框颜色
                borderOpacity: 100,//边框透明度
                opacity: 100,//背景色透明度
                borderRadius: 3,//圆角
                borderWidth: 2,//线的宽度
                backgroundColor: 'rgba(66,133,244,0.1)',

            }
            //添加素材图片默认是gif图第一张
            if (component.type == 'image') {
                styleDef["mode"] = "material"
                styleDef["imgName"] = "gif"
                styleDef.backgroundColor = '';
            }
            let titleDef = {
                background: "system",//背景类型
                bgImage: 1,//背景图,默认系统图的第1张
                customImage: '',//自定义背景图
                customColor: '#4285f4',//自定义背景颜色
                borderColor: '#4285f4',//边框颜色
                borderOpacity: 100,//边框透明度
                opacity: 100,
                borderRadius: 3,//圆角
                borderWidth: 2,//线的宽度
                fontSize: 16,//标题大小
                titleColor: '#ffffff',//标题字体颜色
                fontWeight: 'bold',//是否加粗
                textAlign: 'left',//对齐方式
            }
            //无边框控件
            let name = ['text', 'realTime', 'weather', 'numerical', 'iconfont']
            if (name.includes(component.type)) {
                styleDef.background = 'none'
            }
            config.styles = config.styles ? Object.assign(config.styles, styleDef) : styleDef;
            config.titleStyle = config.titleStyle ? Object.assign(config.titleStyle, titleDef) : titleDef;
            let obj = {
                'width': 500,//元素宽度
                'height': 400,//元素高度
                'top': 100,//元素初始化top位置
                'left': 10,//元素初始化left位置
                'draggable': true,//是否可以拖拽
                'resizable': true,//是否可以控制元素拖拽大小
                'minw': 30,//拖拽元素最小的宽度
                'minh': 30,//拖拽元素最小的高度
                'axis': 'both',//定义元素可拖动的轴。 可用值为x，y，both或none
                'parentLim': true,//是否可以拖出去范围
                'snapToGrid': false,
                'aspectRatio': false,
                'zIndex': 1,//定义组件的zindex(层级)
                'color': '#f9fafc',//元素背景色
                'active': false,//是否选中
                'id': config.key,
                'adaptWidth': 0,
                'coordinate': 0,
                'type': component.type,
                'config': config,//配置项
            }
            //针对每个栏目添加是大小修改
            switch (component.type) {
                case 'text':
                    obj.width = 270
                    obj.height = 45
                    break;
                case 'realTime':
                    obj.width = 300
                    obj.height = 45
                    break;
                case 'weather':
                    obj.width = 670
                    obj.height = 50
                    break;
                case 'image':
                    obj.width = 200
                    obj.height = 200
                    break;
                case 'iconfont':
                    obj.width = 100
                    obj.height = 100
                    break;
            }
            //判断那个栏目需要默认展开标题
            let title = ['chart', 'numerical']
            if (title.includes(obj.type)) {
                obj.config.showTitle = true
            }
            this.screenConfig.components.push(obj);
            //操作记录
            this.addRecal(this.screenConfig);
        },
        //引入图表
        introduceChart(){
            let self=this;
            Util.open({
                component:ScreenChartManageDialog,
                curVm:this,
                widthHeight: ['1000px', '600px'],
                data:{},
                title: this.componentI18n("screenChart")
            },function (action,data){
                if(action!='ok'){
                    return;
                }
                let config = JSON.parse(data.config);
                let json={
                    type:"chart",
                    chartType:config.chartType,
                    title:config.title,
                    config:config
                }
                self.add(json);
            });
        },
        //添加撤回记录
        addRecal: debounce(function (val) {
            this.operationLogs.push(JSON.parse(JSON.stringify(val)));
            this.curIndex = this.operationLogs.length - 1;
        }, 500),
        spreadClick() {
            this.spread = !this.spread;
            let set = this;
            setTimeout(function () {
                let odiv = document.getElementById('freedom');
                if (odiv) {
                    set.scrollWidth = odiv.scrollWidth;
                }
                set.rxDrag()
            }, 300)
        },
        pitchOnKey(key) {
            this.pitchOn = 0
            let component = "";
            this.screenConfig.components.filter(res => {
                res.active = key.indexOf(res.id) >= 0 ? true : false;
                if (res.child) {
                    res.child.filter(ther => {
                        ther.active = key.indexOf(ther.id) >= 0 ? true : false;
                    })
                }
                if (key.indexOf(res.id) >= 0 && !res.child) {
                    this.pitchOn++;
                    component = res;
                }
                return res
            })
            this.rxDrag()
        },
        onBlur(obj) {
            this.screenConfig.components.filter(res => {
                if (res.child) {
                    if (res.id == obj.id) {
                        res.name = obj.name
                    }
                }
            })
            this.rxDrag()
        },
        rxDrag() {
            this.keyShow = new Date().getTime();
        },
        getFilePath(fileId) {
            let token = TokenUtil.getToken();
            fileId = Util.encryptWord(fileId);
            return "/api/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
        },
        getImage(url) {
            return import.meta.env.JPAAS_BASE_URL + url;
        },
        designKeyChange() {
            if (this.designKey == "design") {
                this.initJsScript(this.screenView.jsScript);
            }
        },
        //结束拖拽
        loosenMouse(obj) {
            //当前有撤回过则将当前再记录一次
            if (this.curIndex != 0 && this.curIndex != this.operationLogs.length - 1) {
                let old = this.operationLogs[this.curIndex];
                this.operationLogs.push(JSON.parse(JSON.stringify(old)));
            }
            //操作记录
            this.addRecal(this.screenConfig, this);
        },
        mouseup(type) {
            if (this.$refs[type.id] && this.$refs[type.id].length>0 && this.$refs[type.id][0].mouseup) {
                this.$refs[type.id][0].mouseup()
            }
        },
        init() {
            ScreenViewManageApi.get(this.pkId).then(res => {
                if (res && res.success) {
                    this.screenView = res.data;
                    if (!this.screenView.jsScript) {
                        this.screenView.jsScript = this.defJsScript;
                    }
                    if (res.data.mobileConfig) {
                        this.mobileConfig = JSON.parse(res.data.mobileConfig)
                    }
                    this.screenConfig = JSON.parse(this.screenView.config.replace(/\n/g,"\\n").replace(/\t/g,"\\t"));
                    //操作记录
                    this.addRecal(this.screenConfig);
                    this.initJsScript(this.screenView.jsScript);
                }
            });
        },
        isString(value) {
            return typeof value === 'string';
        },
        save(isPreview) {
            let res = this.vaildScreenView(this.screenView);
            if (!res.success) {
                this.visible = true;
                this.$message.warning(res.message);
                return;
            }
            let self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                zIndex: 20000,
                content: this.i18n("msa.saveMsa", "您确定要保存吗？"),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    self.screenView.config = JSON.stringify(self.screenConfig);
                    self.screenView.mobileConfig = JSON.stringify(self.mobileConfig)
                    if (self.appId) {
                        self.screenView.appId = self.appId;
                    }
                    if(!self.isString(self.screenView.name)){
                        self.screenView.name = JSON.stringify(self.screenView.name)
                    }
                    ScreenViewManageApi.save(self.screenView).then(res => {
                        if (!res.success) {
                            return;
                        }
                        if (isPreview) {
                            let url = "/screen/preview/" + res.data.alias;
                            if(self.appId){
                              url += "?appId="+self.appId;
                            }
                            window.open(url);
                        }
                        setTimeout(() => {
                            let url = "/screen/design/" + res.data.pkId;
                            if (self.appId) {
                                url += "?appId=" + self.appId
                            }
                            window.location.href = url;
                        }, 500)
                    });
                },
                onCancel() {
                }
            })
        },
        vaildScreenView(screenView) {
            if (!screenView.name) {
                return {success: false, message: this.i18n("msa.nameTips", "名称不能为空！"),}
            } else if (!screenView.alias) {
                return {success: false, message: this.i18n("msa.aliasTips", "别名不能为空！")}
            } else if (!screenView.categoryId) {
                return {success: false, message: this.i18n("msa.classifyTips", "分类不能为空！")}
            }
            return {success: true, message: ""}
        },
        emit() {
            let self = this;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                zIndex: 20000,
                content: this.i18n("msa.quitTips", '您确定要退出吗？'),
                okText: this.i18n("index.saveExit", '保存退出'),
                cancelText: this.i18n("index.justQuit", '直接退出'),
                onOk() {
                    let res = self.vaildScreenView(self.screenView);
                    if (!res.success) {
                        self.visible = true;
                        self.$message.warning(res.message);
                        return;
                    }
                    if(!self.isString(self.screenView.name)){
                        self.screenView.name = JSON.stringify(self.screenView.name)
                    }
                    self.screenView.config = JSON.stringify(self.screenConfig);
                    ScreenViewManageApi.save(self.screenView).then(res => {
                        if (!res.success) {
                            return;
                        }
                        setTimeout(() => {
                            let item = {
                                name: "screenViewManage",
                            }

                            if (self.appId) {
                                item["query"] = {
                                    appId: self.appId
                                }
                            }
                            self.$router.push(item);
                        }, 500)
                    });

                },
                onCancel() {
                    let item = {
                        name: "screenViewManage",
                    }
                    if (self.appId) {
                        item["query"] = {
                            appId: self.appId
                        }
                    }
                    self.$router.push(item);
                }
            })
        },
        onClose() {
            if (this.curComponent && !this.curComponent.config.title) {
                this.$message.warning(this.i18n("msa.headersTips", "标题不允许为空!"));
                return;
            }
            this.visible = false;
            this.curComponent = "";
        },
        refresh: debounce(function (ary) {
            this.screenConfig.components = ary;
            this.$forceUpdate();
        }, 1000),
        groupingDesign(list, show) {
            if (show) {
                this.pitchOn = 0
            }
            this.screenConfig.components = list;
            let scrollTop = document.getElementById('rxDragId').scrollTop;
            this.rxDrag()
            //获取滚动条高度
            //操作记录
            this.addRecal(this.screenConfig);
            setTimeout(function () {
                document.getElementById("rxDragId").scrollTop = scrollTop
            }, 10)
        },
        editComponent(component) {
            this.curComponent = component;
            this.visible = true;
        },
        getStyle(type, rect) {
            if (rect == ('image' || 'iconfont')) {
                return
            }
            if (type.background == 'system') {
                //系统自定义
                let img = import.meta.env.JPAAS_BASE_URL + '/image/background/border' + type.bgImage + '.png';
                const style = {borderImageSource: 'url(' + img + ')'};
                return style;
            } else if (type.background == 'custom') {
                //上传图片
                let img = this.getFilePath(type.customImage)
                const style = {
                    backgroundImage: 'url(' + img + ')',
                    backgroundSize: '100% 100%',
                    padding: '0px 15px 15px 15px'
                };
                return style;
            } else if (type.background == 'color') {
                const style = {
                    background: type.customColor,
                    border: this.initBorder(type),
                    borderRadius: type.borderRadius + 'px',
                    padding: '0px 15px 15px 15px'
                };
                return style;
            }
        },
        initBorder(type) {
            if (type.borderOpacity === 0) {
                return 'nome'
            } else {
                return  type.borderWidth + "px solid " +type.borderColor
            }
        },
        getHistory() {
            this.showHistory = true;
        },
        onHistoryClose() {
            this.showHistory = false;
        },
        //回滚历史
        rollbackHistory(config, selectIndex) {
            this.showHistory = false;
            this.versionsId = selectIndex
            this.keyShow = new Date().getTime();
            this.screenConfig = config;
        },
        //撤回
        recall() {
            if (this.curIndex === 0) {
                return;
            }
            this.curIndex--;
            this.screenConfig = JSON.parse(JSON.stringify(this.operationLogs[this.curIndex]))
            this.rxDrag();
        },
        //重做
        reform() {
            if (this.curIndex === this.operationLogs.length - 1) {
                return;
            }
            this.curIndex++;
            this.screenConfig = JSON.parse(JSON.stringify(this.operationLogs[this.curIndex]));
            this.rxDrag();
        },
        //点击选中事件筛选选中那些
        deselect(type) {
            if (type) {
                setTimeout(res => {
                    let _pitchOn = 0
                    this.screenConfig.components.filter(res => {
                        if (res.active) {
                            _pitchOn++
                        }
                    })
                    this.pitchOn = _pitchOn
                }, 500)
            } else {
                this.pitchOn = 0
            }
        },
        //复制
        copyComponent(item) {
            let component = this.getComponent(item.type, this.componentList);
            let obj = JSON.parse(JSON.stringify(item));
            obj.key = Util.randomId();
            obj.id = Math.random() * 1000;
            obj.title = component.title + obj.key;
            obj.config.key = obj.key;
            obj.config.title = obj.title;
            obj.top += 30;
            obj.left += 30;
            obj.active = false;
            obj.zIndex = this.screenConfig.components.length + 1;
            this.screenConfig.components.push(obj);
            //操作记录
            this.addRecal(this.screenConfig);
        },
        getComponent(type, components) {
            for (let i = 0; i < components.length; i++) {
                let component = components[i];
                if (component.type == type) {
                    return component;
                }
                if (component.childList) {
                    component = this.getComponent(type, component.childList);
                    if (component) {
                        return component;
                    }
                }
            }
        },
        //判断是否展示边框
        borderShow(type) {
            let list = ['none', 'color', 'custom'];
            if (list.indexOf(type) != -1) {
                return true
            } else {
                return false
            }
        },
        //放大全屏
        enlarge(obj) {
            this.fullScreen = obj;
            this.fullScreenShow = true
        },
        minification() {
            this.fullScreenShow = false
        },
        mobileObj(obj) {
            this.mobileConfig = obj
        },
        jsScriptChange(value){
            this.screenView.jsScript = value;
        }
    },
    watch: {},
}
</script>

<style scoped>
.ScreenViewManageEdit-tab ::v-deep(.ant-tabs-nav-wrap){
    padding-left: 20px;
}
.ScreenViewManageEdit-tab >>> .ant-tabs-content {
    height: 100%;
}

.ScreenViewManageEdit-button-hover {
    background-color: #4285f4;
    color: white;
    border-radius: 4px;
}

.ScreenViewManageEdit-button:hover {
    background-color: #4285f4;
    color: white;
    border-radius: 4px;
}

.ScreenViewManageEdit-button {
    display: flex;
    padding: 0px 10px;
    height: 32px;
    font-size: 14px;
    justify-content: center;
    align-items: center;
    line-height: 32px;
    cursor: pointer;
}

.ScreenViewManageEdit-button:nth-child(1) {
    margin-right: 37px;
}

.ScreenViewManageEdit-button i {
    margin-right: 12px;
}

.ScreenViewManageEdit-head-button {
    flex: 1;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
}

.componentList-child-commom-list {
    display: flex;
    flex-wrap: wrap;
}

.componentList-child-commom-list-name {
    width: 69px;
    height: 63px;
    border-radius: 5px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
    margin-right: 10px;
    cursor: pointer;
}

.componentList-child-commom-list-name:hover {
    background-color: #eff5ff;
}

.componentList-child-commom-list-name >>>.rx-icon {
    font-size: 25px;
    color: #9cbff9;
    margin-top: 10px;
    margin-bottom: 5px;
}

.componentList-child-commom-list-name span {
    font-size: 12px;
    color: #808080;
}

.componentList-child-commom-hend {
    height: 50px;
    line-height: 50px;
    color: #333333;
    font-size: 14px;
    border-bottom: 1px solid #dedede;
}

.componentList-child {
    width: 425px;
    min-height: 200px;
    max-height: 600px;
    overflow: auto;
    background-color: #ffffff;
    border: solid 1px #dedede;
    position: absolute;
    top: 63px;
    left: -170px;
    padding: 0px 20px 10px 20px;
    z-index: 10000;
    display: none;
}

.rx-dragList-common {
    width: 100%;
    height: 100%;
    padding: 0px !important;
}

.rx-dragList-common-system {
    width: 100%;
    height: 100%;
    border-image-slice: 15 fill;
    border-width: 15px;
    border-style: solid;
    overflow: hidden;
    background-clip: padding-box;
    filter: blur(0px
    );
}

.system-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.drawer-button {
    display: flex;
    flex-direction: column;
    position: fixed;
    cursor: pointer;
    z-index: 9;
    top: 160px;
    right: 0px;
    width: 41px;
    background-size: 100% 100%;
    height: 133px;
    text-align: center;
    background-image: url("@img/width.png");
}

.drawer-button span {
    margin-top: 55px;
    font-size: 25px;
    width: 55px;
}

.right-design {
    background-color: red;
}

.right-design >>> .ant-drawer-body {
    padding: 0px !important;
    overflow: hidden;

}

.right-design >>> .ant-tabs-tabpane-active {
    padding: 0px 20px;
}

.right-design >>> .ant-tabs-tabpane-active:nth-child(2) {
    padding: 0px 0px 0px 20px !important;
}

.ScreenViewManageEdit-drag-common {
    flex: 1;
    overflow: auto;
    position: relative;
}

.ScreenViewManageEdit-drag-common-img {
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
}

.ScreenViewManageEdit-drag-le {
    width: 200px;
    border-right: 1px solid #dedede;
}

.ScreenViewManageEdit-drag-le-spread {
    overflow-x: hidden;
    width: 64px;
    border-right: 1px solid #dedede;
}

.ScreenViewManageEdit-drag {
    flex: 1;
    overflow: hidden;
    display: flex;
}

.ScreenViewManageEdit {
    display: flex;
    height: 100%;
    flex-direction: column;
}

.ScreenViewManageEdit-head {
    height: 60px;
    background-color: #040a24;
    display: flex;
    align-items: center;
}

.ScreenViewManageEdit-head-le img {
    width: 35px;
    margin-left: 14px;
}

.ScreenViewManageEdit-head-le span {
    font-size: 18px;
    color: #ffffff;
    margin-left: 10px;
}

.ScreenViewManageEdit-head-ri {
    display: flex;
    margin-right: 12px;
}

.ScreenViewManageEdit-head-ri-button {
    color: white;
    display: flex;
    flex-direction: column;
    font-size: 12px;
    margin: 0px 12px;
    cursor: pointer;
}

.ScreenViewManageEdit-head-ri-button-iconfont {
    color: white;
    text-align: center;
}
.ScreenViewManageEdit-head-ri-button-iconfont>>>.rx-icon{
    font-size: 20px;
    margin-bottom:2px;
}
.ScreenViewManageEdit-control {
    height: 64px;
    border-bottom: 1px solid #dedede;
    display: flex;
    align-items: center;
}

.ScreenViewManageEdit-control-common-type {
    position: relative;
}

.ScreenViewManageEdit-control-common {
    display: flex;
    flex-direction: column;
    padding:10px;
    cursor: pointer;
    min-width: 75px;
    border-radius: 4px;
}

.ScreenViewManageEdit-control-common:hover {
    background-color: #eff1f5;
    border-radius: 4px;
}

.ScreenViewManageEdit-control-common-type:hover > .componentList-child {
    display: block;
}

.ScreenViewManageEdit-control-icon {
    color: #4285f4;
    text-align: center;
    margin-bottom: 5px;
}

.ScreenViewManageEdit-control-icon >>> .rx-icon {
    font-size: 24px !important;
}

.ScreenViewManageEdit-control-name {
    font-size: 12px;
    color: #333333;
    text-align: center;
}

.ScreenViewManageEdit-drag {

}

.mobile-compile {
    margin-right: 5px;
    cursor: pointer;
    opacity: 0.8;
}

.mobile-compile:hover {
    opacity: 1;
}
.Loading {
    position: fixed;
    width: 100%;
    height: 100%;
    display: flex;
    text-align: center;
    justify-items: center;
    align-items: center;
    background-color: rgba(0, 0, 0, .45);
    z-index: 99;
}

.ScreenViewManageEdit-head-ri-button-forbid {
    cursor: no-drop
}

.ScreenViewManageEdit-head-ri-button-forbid {
    opacity: .5;
}
</style>
